var COOKIE_KEY_DEFAULT_ADDRESS_ID = "DEFAULT_ADDRESS__ID";



var app = new Framework7({
    modalTitle: '温馨提示',
    pushState: true,

    onAjaxStart: function (xhr) {
        app.showIndicator();
    },
    onAjaxComplete: function (xhr) {
        app.hideIndicator();
    }
});

var $ = Dom7;

var mainView = app.addView('.view-main', {
    dynamicNavbar: true
});

var issuesSelectedItems={},issuesTotalPrice=0,issuesDeviceInfo={};


// 选择框初始化
function SelectBoxInit(obj,itemEleName,isSingle,callback) {
    $(obj).on('click', function () {
        if (isSingle) {
            //单选
            $(this).parent().find(itemEleName + '.selected').removeClass("selected");
            $(this).addClass("selected");
        } else {
            if ($(this).hasClass("selected")) {
                $(this).removeClass("selected");
            } else {
                $(this).addClass("selected");
            }
        }

        callback($(this).data("val"), $(this));
    });
}



//维修页面
app.onPageInit('fix-page', function (page) {
    issuesSelectedItems={};
    var versionId = page.query.vid;
    var pageObj = $('.page[data-page="fix-page"]');
    var selected_color_attr;
    var selected_attr_count = 0;
    var orderType = page.query.ordertype;

    SelectBoxInit(pageObj.find('.select-list-block li:not(.color-attr-item)'), 'li', false, function () {
        selected_attr_count = pageObj.find('.select-list-block li.selected').length;
        $("#total-fix-count").html(selected_attr_count);
        if (selected_attr_count > 0 && selected_color_attr) {
            pageObj.find('.btn-confirm-order').removeClass("btn-disable");
        } else {
            pageObj.find('.btn-confirm-order').addClass("btn-disable");
        }

        var totalPrice = 0;
        $.each(pageObj.find('.select-list-block li.selected'), function (index, obj) {
            totalPrice += parseFloat($(obj).data("price"));
        });
        issuesTotalPrice=totalPrice;
        $("#total-fix-price").html("￥" + totalPrice);
    });


    SelectBoxInit(pageObj.find('.color-attr-item .item-color'), '.item-color', true, function (val, obj) {
        selected_color_attr = val;
		issuesDeviceInfo["colorId"]=val;
		issuesDeviceInfo["colorText"]=$(obj).data("text");
        if (selected_attr_count > 0) {
            pageObj.find('.btn-confirm-order').removeClass("btn-disable");
        } else {
            pageObj.find('.btn-confirm-order').addClass("btn-disable");
        }

		$(".selected-device-name").html(issuesDeviceInfo["name"] + " (" + $(obj).data("text") + ")");
        //$(".selected-device-name").html($(".selected-device-name").data("basetext") + " (" + $(obj).data("text") + ")");
        $('.page[data-page="fix-page"] .page-content').scrollTop(120, 400);

    });



    pageObj.find('.btn-confirm-order').on('click', function () {
        if (!selected_color_attr) {
            app.alert("请选择设备颜色！");
            return;
        }
        if (!selected_attr_count) {
            app.alert("请至少选择一项故障项目！");
            return;
        }
	

        if (!$(this).hasClass("btn-disable")) {

			$.each($('.page[data-page="fix-page"] .select-list-block li.selected'), function (index, obj) {
                   var val=$(obj).data("val");
				   var title=$(obj).find(".item-context").text();
                   issuesSelectedItems[val]=title;
            });
            var url="device_repair/order-confirm.php?ids=" + GetFixSelectedIds() + "&vid=" + versionId + "&color=" + selected_color_attr + "&ordertype=" + orderType;
			//app.alert(url);
            mainView.router.loadPage(url);
        }
    });

});


//升級页面
app.onPageInit('upgrade-page', function (page) {
    issuesSelectedItems={};
    var versionId = page.query.vid;
    var pageObj = $('.page[data-page="upgrade-page"]');
    var selected_color_attr;
    var selected_attr_count = 0;
    var orderType = page.query.ordertype;



    pageObj.find('.sub-level-item').on('click', function () {
        pageObj.find('.sub-level-item').removeClass("active");
        $(this).addClass("active");
        var totalPrice = 0;
		$.each(pageObj.find('.active'), function (index, obj) {
			var price=$(obj).data("price");
			console.log(price);
            totalPrice += parseFloat(price);
        });
        issuesTotalPrice=totalPrice;
        $("#total-fix-price").html("￥" + totalPrice);
        pageObj.find('.btn-disable').removeClass('btn-disable');


    });




    pageObj.find('.btn-confirm-order').on('click', function () {

        //if (!selected_attr_count) {
        //    app.alert("请至少选择一项升級项目！");
        //    return;
        //}
	

        if (!$(this).hasClass("btn-disable")) {

			$.each($('.page[data-page="upgrade-page"] .active'), function (index, obj) {
                   var val=$(obj).data("val");
				   var title=$(obj).text();
                   issuesSelectedItems[val]=title;
            });
            var url="device_upgrade/order-confirm.php?vid=" + versionId + "&color=" + selected_color_attr + "&ordertype=" + orderType;
			//app.alert(url);
            mainView.router.loadPage(url);
        }
    });

});

//回收页面
app.onPageInit('recovery-page', function (page) {

    var versionId = page.query.vid;
    var pageObj = $('.page[data-page="recovery-page"]');
    var PlanList;
    var selected_color_attr;
    var orderType = page.query.ordertype;

	var url="device_upgrade/ajax.php?action=getSettings";
	var pdata={vid:versionId};
	$.post(url,pdata,function(str){
	
		var data=eval('('+str+')');
        console.log(data);
        PlanList = data.list;
	});
	/*
    $.ajax({
        type: "POST",
        url: "/GetPlanListByVersionId",
        data: { VersionId: versionId },
        dataType: "json",
        success: function (data) {
            console.log(data);
            PlanList = data.list;
        }
    });
    */



    pageObj.find('.sub-level-item').on('click', function () {
        $(this).parent().parent().find(".sub-level-item.active").removeClass("active");
        $(this).addClass("active");
        $("#total-fix-count").html(pageObj.find('.sub-level-item.active').length);

        var offset = $(this).parent().parent().offset().top + $('.page[data-page="recovery-page"] .page-content').scrollTop();
        $('.page[data-page="recovery-page"] .page-content').scrollTop(offset, 500);

        if ($(this).hasClass('color-level-item')) {
            selected_color_attr = $(this).data("id");
        }



        $('#total-fix-price').html('请选择完整属性3');

        var isNeedShowBtn;
        //先判断页面是否存在颜色属性
        if (pageObj.find('.color-level-item').length == 0) {
            //如果没有颜色属性
            if (pageObj.find('.sub-level-item.active:not(.color-level-item)').length > 0) {
                isNeedShowBtn = true;
            }
        }else
        {
            if (pageObj.find('.sub-level-item.active:not(.color-level-item)').length > 0 && pageObj.find('.color-level-item.active').length > 0) {
                isNeedShowBtn = true;
            }
        }

        if (isNeedShowBtn) {
            var selectedIds = GetRecoverySelectedIds();
            for (var i = 0; i < PlanList.length; i++) {
                if (selectedIds == PlanList[i].PlanList) {
                    pageObj.find('.btn-disable').removeClass('btn-disable');
                    $('#total-fix-price').html('￥' + PlanList[i].PlanPrice);
                    return;
                }
            }
        }
    });


    pageObj.find('.btn-confirm-order').on('click', function () {
        if (!PlanList) {
            app.alert("请至少选择一项属性！");
            return;
        }

        if (!$(this).hasClass("btn-disable")) {
            mainView.router.loadPage("device_repair/confirm-form.php?ids=" + GetRecoverySelectedIds() + "&vid=" + versionId + "&color=" + (selected_color_attr ? selected_color_attr : "0") + "&ordertype=" + orderType);
        }
    });


});



//选择设备页面
app.onPageInit('select-device-page', function (page) {

    var pageObj = $('.page[data-page="select-device-page"]');

    pageObj.find('.sub-level-item').on('click', function () {
        pageObj.find('.sub-level-item').removeClass("active");
        $(this).addClass("active");

        var brandType = $("#txtBrandType").val();

		var did=$(this).data("id");
		issuesDeviceInfo["id"]=did;
		issuesDeviceInfo["name"]=$(this).text();
        if (brandType == '1') {
            mainView.router.loadPage("device_repair/issue-select.php?vid=" + did + "&ordertype=phonefix");
        } else if (brandType == '2') {
            mainView.router.loadPage("device_repair/issue-select.php?vid=" + did + "&ordertype=padfix");
        }else if (brandType == '3') {
            mainView.router.loadPage("/Recovery/" + $(this).data("id") + "?vid=" + $(this).data("id") + "&ordertype=recovery");
        } else if (brandType == '4') {
            mainView.router.loadPage("device_upgrade/item-select.php?vid=" + $(this).data("id") + "&ordertype=memoryup");
        }
    });
});

//提现页面
app.onPageInit('user-takecash-page', function (page) {

    var pageObj = $('.page[data-page="user-takecash-page"]');
    var payType = "1";
    // 支付类型选择
    SelectBoxInit(pageObj.find('.takecash-type-select li'), 'li', true, function (val) {
        payType = val;
        if (payType == "1") {
            pageObj.find('.item-payaccount-title').html("支付宝账户");
            pageObj.find('.txtTakeCashAccount').attr("placeholder", "请输入支付宝账户");
            pageObj.find('.group-sel-bank-type').hide();
            pageObj.find('.group-txt-bank-client').hide();
        } else if (payType == "2") {
            pageObj.find('.item-payaccount-title').html("银行卡号");
            pageObj.find('.txtTakeCashAccount').attr("placeholder", "请输入银行卡号");
            pageObj.find('.group-sel-bank-type').show();
            pageObj.find('.group-txt-bank-client').show();
        }
    });

    pageObj.find('.btn-takecash').on('click', function () {

        var applyMoney = pageObj.find('.txtTakeCashMoney').val();
        var payTypeString = "未知";

        if (applyMoney.length == 0) {
            app.alert("请输入提现金额！");
            return;
        }

        if (parseFloat(applyMoney) == 0) {
            app.alert("请输入大于0的提现金额！");
            return;
        }

        var payInfo = "";
        if (payType == "1") {
            payTypeString = "支付宝";
            if (pageObj.find(".txtTakeCashAccount").val().length == 0) {
                app.alert("请输入支付宝账户！");
                return;
            }
            payInfo = pageObj.find(".txtTakeCashAccount").val();
        } else if (payType == "2") {
            payTypeString = $(".sel-bank-type").val();
            if (pageObj.find(".txtTakeCashAccount").val().length == 0) {
                app.alert("请输入银行卡号！");
                return;
            }
            if (pageObj.find(".txtTakeCashClientName").val().length == 0) {
                app.alert("请输入银行卡持有人姓名！");
                return;
            }
            payInfo = pageObj.find(".txtTakeCashAccount").val() + " " + pageObj.find(".txtTakeCashClientName").val();
        }


        app.showIndicator();
        $.ajax({
            type: "POST",
            url: "/SaveTakeCashApply",
            data: { ApplyMoney: applyMoney, PayInfo: payInfo, payType: payTypeString },
            dataType: "json",
            error: function () {
                app.alert("申请提现失败！");
            },
            success: function (data) {
                if (data.success) {
                    app.hideIndicator();
                    mainView.router.loadPage("/TakeCashSuccess?lid=" + data.logId);
                } else {
                    app.hideIndicator();
                    app.alert(data.msg);
                }
            }
        });



    });


    pageObj.find('.hk-tab .tab-item').on('click', function () {
        $(this).parent().find(".active").removeClass("active");
        $(this).addClass("active");
        $(".tab-context").hide();
        $(".tab-context[data-index='" + $(this).data("index") + "']").show();
    });
});


//确认订单页面
app.onPageInit('confirm-order-page', function (page) {
    console.log(page.query);
   
    var pageObj = $('.page[data-page="confirm-order-page"]');

    var mServiceType = "1";
    var mOrderType = page.query.ordertype;
    var mVersionId = page.query.vid;
    var mPlanIdList = page.query.ids;
    var mDeviceColor = page.query.color;
    var mPayCheckoutType = 0;
    var mPayCheckoutAlipayAccount;
    var mPayCheckoutAlipayName;

	/*
    $.ajax({
        type: "POST",
        url: "/GetConfirmOrderInfo",
        data: { ids: mPlanIdList, vid: mVersionId, color: mDeviceColor },
        dataType: "json",
        success: function (data) {
            console.log(data);
            pageObj.find('.lblOrderInfo').html(data.OrderInfo);
            pageObj.find('.lblOrderVersionId').html(data.VersionName + " " + data.DeviceColor);
            pageObj.find('.lblOrderPrice').html("￥" + data.TotalPrice);
        }
    });
	*/
     var orderinfo="",versioninfo="";
     for(var k in issuesSelectedItems){
	    var title=issuesSelectedItems[k];
        orderinfo+=title+",";
	 }
	 pageObj.find('.lblOrderInfo').html(orderinfo);

	var deviceColor=issuesDeviceInfo["colorText"]|"";

	versioninfo=issuesDeviceInfo["name"]+" "+ deviceColor;

	pageObj.find('.lblOrderVersionId').html(versioninfo);
    pageObj.find('.lblOrderPrice').html("￥" + issuesTotalPrice);

    LoadDefaultUserAddress();

    // 服务类型选择
    SelectBoxInit(pageObj.find('.service-type-select li'), 'li', true, function (val) {
        mServiceType = val;
        if (val == "1") {
            //上门
            pageObj.find('.item-title-sub-select-1').html("上门地址");
            pageObj.find('.item-title-sub-select-2').html("上门时间");
            pageObj.find('.post-contact-item').hide();
            pageObj.find('.post-type-item').hide();
            pageObj.find('.post-input-postid-item').hide();
            pageObj.find('.post-input-postname-item').hide();
            pageObj.find('.post-input-postphone-item').hide();
            pageObj.find('.post-input-postaddr-item').hide();
            pageObj.find('.selcet-come-time').show();
            //post-input-postname-item
            //post-input-type-item
            LoadDefaultUserAddress();
        } else {
            //邮寄
            pageObj.find('.item-title-sub-select-1').html("邮寄地址");
            pageObj.find('.selcet-come-time').hide();
            pageObj.find('.post-contact-item').show();
            pageObj.find('.post-type-item').show();
            pageObj.find('.post-input-postid-item').show();
            pageObj.find('.post-input-postname-item').show();
            pageObj.find('.post-input-postphone-item').show();
            pageObj.find('.post-input-postaddr-item').show();

            //post-input-postid-item
            pageObj.find('.item-title-address').html("广州市白云区新市墟太阳广场一层C19");
        }
    });

    // 支付类型选择
    SelectBoxInit(pageObj.find('.pay-type-select li'), 'li', true, function (val) {
        mPayCheckoutType = val;
        if (val == "1") {
            pageObj.find('.pay-item-input-1').show();
            pageObj.find('.pay-item-input-2').show();
        } else if (val == "2") {
            pageObj.find('.pay-item-input-1').hide();
            pageObj.find('.pay-item-input-2').hide();
        } else if (val == "3") {
            pageObj.find('.pay-item-input-1').hide();
            pageObj.find('.pay-item-input-2').hide();
        }
    });

    $('.confirm-item .del').on('click', function () {
        var itemObj = $(this).parent();
        app.confirm('确定要删除此项?', function () {
            $(itemObj).remove();
        });
    });


    pageObj.find('.selcet-address').on('click', function () {
        if (mServiceType == "1") {
            //如果是上门才可点击选择地址
            mainView.router.loadPage("customer/contact-select.php");
        }
    });


    if (mOrderType == "phonefix") {
        //pageObj.find('.confirm-pay-type-warp').hide();
        pageObj.find('.confirm-order-type').html("手机维修");
        pageObj.find('.item-title-select-1').html("上门维修");
        pageObj.find('.item-title-select-2').html("到店/邮寄维修");
        pageObj.find('.lblOrderInfoTitle').html("故障项目：");
        pageObj.find('.lblOrderPriceTitle').html("预估价格：");
        pageObj.find('.lblOrderOtherInfo').show();

    } else if (mOrderType == "padfix") {
        //pageObj.find('.confirm-pay-type-warp').hide();
        pageObj.find('.confirm-order-type').html("平板维修");
        pageObj.find('.item-title-select-1').html("上门维修");
        pageObj.find('.item-title-select-2').html("到店/邮寄维修");
        pageObj.find('.lblOrderInfoTitle').html("故障项目：");
        pageObj.find('.lblOrderPriceTitle').html("预估价格：");
        pageObj.find('.lblOrderOtherInfo').show();
    } else if (mOrderType == "recovery") {
        //pageObj.find('.confirm-pay-type-warp').show();
        pageObj.find('.confirm-order-type').html("手机回收");
        pageObj.find('.item-title-select-1').html("上门回收");
        pageObj.find('.item-title-select-2').html("到店/邮寄回收");
        pageObj.find('.lblOrderInfoTitle').html("手机详情：");
        pageObj.find('.lblOrderPriceTitle').html("手机估价：");
        pageObj.find('.lblOrderOtherInfo').hide();
    } else if (mOrderType == "memoryup") {
        //pageObj.find('.confirm-pay-type-warp').show();
        pageObj.find('.confirm-order-type').html("容量升级");
        pageObj.find('.item-title-select-1').html("上门服务");
        pageObj.find('.item-title-select-2').html("到店/邮寄维修");
        pageObj.find('.lblOrderInfoTitle').html("服务详情：");
        pageObj.find('.lblOrderPriceTitle').html("服务估价：");
        pageObj.find('.lblOrderOtherInfo').hide();
    }


    var todayDate = new Date();



    var days = [];
    for (var i = 0; i < 6; i++) {
        var tmpDay = new Date(todayDate.valueOf() + i * 24 * 60 * 60 * 1000);
        days.push(time_string(tmpDay));
    }


    var pickerDescribe = app.picker({
        input: '#picker-come-time',
        rotateEffect: true,
        cols: [
        {
            textAlign: 'left',
            values: days
        },
        {
            values: ('09：00~10：00|10：00~11：00|11：00~12：00|12：00~13：00|13：00~14：00|14：00~15：00|15：00~16：00|16：00~17：00|17：00~18：00|18：00~19：00|19：00~20：00|20：00~21：00|21：00~22：00|').split('|')
        }],
        toolbarCloseText: '确定'
    });



    //btn-confirm-order
    pageObj.find('.btn-confirm-order').on('click', function () {

        //mainView.router.loadPage("/AddressManage");
        var mUserAddressId = pageObj.find('.item-title-address').data("id");
        var mComeTime = $("#picker-come-time").val();

        var mPostId = pageObj.find('.txtPostId').val();
        var mPostName = pageObj.find('.txtPostName').val();
        var mPostCallPhone = pageObj.find('.txtPostCallPhone').val();
        var mPostAddress = pageObj.find('.txtPostAddress').val();
        var orderText = "";
        orderText += "\r\n订单类型：" + mOrderType;
        orderText += "\r\n服务类型：" + mServiceType;
        orderText += "\r\n用户地址：" + mUserAddressId;
        orderText += "\r\n上门时间：" + mComeTime;
        orderText += "\r\n选择项：" + mPlanIdList;
        orderText += "\r\n版本号：" + mVersionId;
        orderText += "\r\n设备颜色：" + mDeviceColor;

        if (mServiceType == 1) {
            if (mUserAddressId <= 0) {
                app.alert("请选择您的上门地址！");
                return;
            }
        } else {
            mUserAddressId = 0;

            if (mPostId.length == 0) {
                app.alert("请输入快递单号！");
                return;
            }

            if (mPostId.length < 12) {
                app.alert("快递单号输入错误！");
                return;
            }

            if (mPostName.length == 0) {
                app.alert("请输入您的姓名！");
                return;
            }

            if (mPostCallPhone.length == 0) {
                app.alert("请输入您的联系方式！");
                return;
            }

            if (mPostCallPhone.length != 11) {
                app.alert("您的联系方式输入错误！");
                return;
            }


            if (mPostAddress.length == 0) {
                app.alert("请输入您的地址！");
                return;
            }


        }
        var payCheckoutInfo = "";
        /*
        if (mOrderType == "recovery" || mOrderType == "memoryup") {
        mPayCheckoutType = pageObj.find('.pay-type-select li.selected').data("val");
        orderText += "\r\n收款类型：" + mPayCheckoutType;
        if (mPayCheckoutType == 1) {
        mPayCheckoutAlipayAccount = $("#txtPayCheckoutAlipayAccount").val();
        mPayCheckoutAlipayName = $("#txtPayCheckoutAlipayName").val();
        if (mPayCheckoutAlipayAccount.length == 0) {
        app.alert("请输入收款支付宝账号！");
        return;
        }
        if (mPayCheckoutAlipayName.length == 0) {
        app.alert("请输入收款支付宝户名！");
        return;
        }
        orderText += "\r\n收款支付宝账户：" + mPayCheckoutAlipayAccount;
        orderText += "\r\n收款支付宝名称：" + mPayCheckoutAlipayName;
        payCheckoutInfo = "支付宝账号：" + mPayCheckoutAlipayAccount + " 支付宝户名：" + mPayCheckoutAlipayName;
        }
        }*/

        app.showIndicator();
		
		var url="payment/ajax.php?action=doSubmit";
		var pdata= {
                PlanIdList: mPlanIdList,
                VersionId: mVersionId,
                DeviceColor: mDeviceColor,

                OrderType: mOrderType,
                ServiceType: mServiceType,
                UserAddressId: mUserAddressId,
                ComeTime: mComeTime,

                PayCheckoutType: mPayCheckoutType,
                PayCheckoutInfo: payCheckoutInfo,

                PostId: mPostId,
                PostInfo: mPostName + " " + mPostAddress,
				PostName: mPostName,
				PostAddress: mPostAddress,
                PostCallPhone:mPostCallPhone
				,remark:orderinfo
			    ,total_price:issuesTotalPrice
            };


		$.post(url,pdata,function(str){
              app.hideIndicator();
			 var json=eval('('+str+')');
             if (json["success"]) {
				    var prefix="device_repair";
				     if(mOrderType=="memoryup"){
						 prefix="device_upgrade";
					 }
                    mainView.router.loadPage(prefix+"/order-success.php?oid=" + json["orderId"]);
             } else {
                    app.alert(json["msg"]);
                    return;
            }
		});


    });

});

//订单支付页面
app.onPageInit('order-pay-page', function (page) {

    var pageObj = $('.page[data-page="order-pay-page"]');
    var orderId = page.query.oid;
    var payType = 1;
    // 支付类型选择
    SelectBoxInit(pageObj.find('.pay-type-select li'), 'li', true, function (val) {
        payType = val;
    });

    if (CheckIsWeixn()) {
        //如果在微信端就隐藏支付宝支付
        pageObj.find('.pay-type-select li').eq(0).removeClass("selected").hide();
        pageObj.find('.pay-type-select li').eq(1).addClass("selected");
        payType = 2;
    }


    var orderPayStatus = pageObj.find("#OrderPayStatus").val();
    if (orderPayStatus == "2") {
        app.alert("此订单已支付！", function () {
            mainView.router.loadPage("/OrderPaySuccess?oid=" + orderId);
        });
    }


    pageObj.find('.btn-confirm-order-pay').on('click', function () {

        if (payType == 2 && !CheckIsWeixn()) {
            app.alert("您现在处于浏览器环境中 请在微信中打开网页进行支付！");
            return;
        }

        var couponId = $('#txt-coupon-value').data("couponid");

        app.showIndicator();
        $.ajax({
            type: "POST",
            url: "/SaveOrderPayType",
            data: { PayType: payType, OrderId: orderId, CouponId: couponId },
            dataType: "json",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
				app.hideIndicator();
                app.alert("请求支付失败！" + textStatus);
            },
            success: function (data) {
                if (data.success) {
                    if (data.payType == 'alipay') {
                        app.hideIndicator();
                        window.location.href = "/SaveOrderPayType_Alipay?oid=" + orderId;
                    }
                    else if (data.payType == 'wechatpay') {
                        app.hideIndicator();
						wx.chooseWXPay({
                            timestamp: data.wechatPay.TimeStamp, //时间戳
                            nonceStr: data.wechatPay.NonceStr, //随机串
                            package: data.wechatPay.Package, //扩展包
                            signType: "MD5", //微信签名方式:MD5
                            paySign: data.wechatPay.PaySign, //微信签名
							complete: function (res) {
								if (res.errMsg == "chooseWXPay:ok") {
									mainView.router.loadPage("/OrderPaySuccess?oid=" + orderId);
								} else if (res.errMsg == "chooseWXPay:cancel") {
									//取消了，不操作
								} else {
									app.alert("支付失败！原因：" + res.errMsg);
								}
							}
                        });
                    } else {
                        app.hideIndicator();
                        mainView.router.loadPage("/OrderPaySuccess?oid=" + orderId);
                    }
                } else {
                    app.hideIndicator();
                    app.alert(data.msg);
                    mainView.router.loadPage("/OrderPaySuccess?oid=" + orderId);
                }
            }
        });
    });

});

//用户登录页面
app.onPageInit('user-login-page', function (page) {
    var reSendTick = 0;
    var reSendInterval;
    var pageObj = $('.page[data-page="user-login-page"]');

    pageObj.find('.btn-login').on('click', function () {


        var _PhoneNumber = pageObj.find('.txtPhoneNumber').val();

        if (_PhoneNumber.length == 0 || _PhoneNumber.length != 11) {
            app.alert("手机号码输入不正确，请检查！");
            return;
        }

        var _PhoneCode = pageObj.find('.txtSMSCode').val();

        if (_PhoneCode.length == 0 || _PhoneCode.length != 6) {
            app.alert("验证码输入不正确，请检查！");
            return;
        }


        app.showIndicator();
        $.ajax({
            type: "POST",
            url: "/CheckLogin",
            data: { phone: _PhoneNumber, code: _PhoneCode },
            dataType: "json",
            success: function (data) {
                app.hideIndicator();
                if (data.success) {
                    app.alert("登录成功！");
                    location.reload();
                } else {
                    app.alert(data.msg);
                }
            }
        });



    });

    pageObj.find('.btn-send-code').on('click', function () {

        if ($(this).hasClass("btn-disable"))
            return;
        var _PhoneNumber = pageObj.find('.txtPhoneNumber').val();

        if (_PhoneNumber.length == 0 || _PhoneNumber.length != 11) {
            app.alert("手机号码输入不正确，请检查！");
            return;
        }

        pageObj.find('.btn-send-code').addClass("btn-disable");
        app.showIndicator();
        $.ajax({
            type: "POST",
            url: "/SendSMSCode",
            data: { phone: _PhoneNumber },
            dataType: "json",
            error: function () {
                //app.alert("请求支付失败！");
            },
            success: function (data) {
                app.hideIndicator();
                if (data.success) {
                    reSendTick = 60;

                    if (reSendInterval) {
                        clearInterval(reSendInterval);
                    }

                    reSendInterval = setInterval(function () {
                        reSendTick--;
                        if (reSendTick <= 0) {
                            pageObj.find('.btn-send-code').removeClass("btn-disable").html("重新发送");
                        } else {
                            pageObj.find('.btn-send-code').addClass("btn-disable").html(reSendTick + "秒后重发");
                        }
                    }, 1000);




                } else {
                    app.alert(data.msg);
                }
            }
        });
    });

});

//选择优惠券页面
app.onPageInit('user-coupon-page', function (page) {
    var pageObj = $('.page[data-page="user-coupon-page"]');
    var isSelect = page.query.isselect;
    var orderPrice = page.query.orderprice;

    if (isSelect) {
        pageObj.find('.use-button').on('click', function () {
            if ($(this).parent().hasClass("coupon-dis"))
                return;
            if (orderPrice) {
                var fullPrice = $(this).data("fullprice");
                if (orderPrice && orderPrice >= fullPrice) {

                    if ($('#txt-coupon-value')) {
                        $('#txt-coupon-value').val("￥" + $(this).data("price"));
                        $('#txt-coupon-value').attr("data-couponid", $(this).data("id"));
                        $("#txt-order-total-price").html("￥" + (orderPrice - $(this).data("price")).toFixed(2));
                    }
                    mainView.router.back();
                } else {
                    app.alert("此优惠券需满足订单金额大于" + fullPrice + "的要求！");
                }
            } else {

            }
        });
    }
});
//添加优惠券页面
app.onPageInit('add-coupon-page', function (page) {
    var pageObj = $('.page[data-page="add-coupon-page"]');
    if (CheckIsWeixn()) {
        pageObj.find(".lblor").show();
        pageObj.find(".coupon-scan").show();
    }
    pageObj.find(".coupon-scan").on('click', function () {
        wx.scanQRCode({
            needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
            scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
            success: function (res) {
                var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                pageObj.find(".txtCouponCode").val(result);
            }
        });
    });

    pageObj.find(".btn-exchange").on('click', function () {
        var couponVal = pageObj.find(".txtCouponCode").val();
        if (couponVal.length == 0) {
            app.alert("请输入兑换码！");
            return;
        }
        app.showIndicator();
        $.ajax({
            type: "POST",
            url: "/CheckCoupon",
            data: {
                CouponCode: couponVal
            },
            dataType: "json",
            success: function (data) {
                app.hideIndicator();
                mainView.router.refreshPreviousPage();
                if (data.success) {

                    app.modal({
                        title: '温馨提示',
                        text: '兑换成功，是否返回？',
                        buttons: [
                          {
                              text: '返回',
                              onClick: function () {
                                  mainView.router.back();
                              }
                          },
                          {
                              text: '继续添加',
                              onClick: function () {
                                  pageObj.find(".txtCouponCode").val("");
                              }
                          }
                        ]
                    })
                } else {
                    app.alert("兑换失败！请检查您的兑换码！");
                }

            }
        });

    });


});


//订单评价页面
app.onPageInit('review-order-page', function (page) {
    var pageObj = $('.page[data-page="review-order-page"]');
    var imageList = [];
    var uploadImageList = [];
    var orderId = page.query.oid;

    pageObj.find('.img-add').on('click', function () {
        if (!CheckIsWeixn()) {
            app.alert("您现在处于浏览器环境中 请在微信中打开上传图片！");
            return;
        }
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                var localIds = res.localIds + ""; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                imageList.push(localIds);
                pageObj.find('.image-list').append('<div class="img-item"><img src="' + localIds + '"/></div>');
            }
        });

    });


    pageObj.find('.review-select-item').on('click', function () {
        pageObj.find('.review-select-item').removeClass("active");
        for (var i = 0; i <= $(this).index(); i++) {
            pageObj.find('.review-select-item').eq(i).addClass("active");
        }
    });



    pageObj.find('.btn-save-review').on('click', function () {
        var reContext = pageObj.find('.txtReviewContext').val();
        var reStarCount = pageObj.find('.review-select-item.active').length;
        if (reContext.length == 0) {
            app.alert("请输入评价内容！");
            return;
        }


        var uploadDoneCount = 0;
        if (imageList.length > 0) {
            for (var i = 0; i < imageList.length; i++) {
                wx.uploadImage({
                    localId: imageList[i], // 需要上传的图片的本地ID，由chooseImage接口获得
                    isShowProgressTips: 1, // 默认为1，显示进度提示
                    success: function (res) {
                        var serverId = res.serverId; // 返回图片的服务器端ID
                        uploadDoneCount++;
                        uploadImageList.push(serverId);
                        if (uploadDoneCount == imageList.length) {
                            SaveReview(orderId, reContext, reStarCount, uploadImageList.join(','));
                        }
                    }
                });
            }
        } else {
            SaveReview(orderId, reContext, reStarCount, null);
        }

        var testStr = "";
        testStr += "\r\n评论内容：" + reContext;
        testStr += "\r\n星数：" + reStarCount;
        testStr += "\r\n图片列表：" + uploadImageList;
        //alert(testStr);
        //return;




    });


});

//选择地址页面
app.onPageInit('select-address-page', function (page) {
    var pageObj = $('.page[data-page="select-address-page"]');

    if (page.query.type == "edit") {
        pageObj.data("update", "true");
    }
    ReloadUserAddressList(page.query.aid);
});


//添加地址页面
app.onPageInit('add-address-page', function (page) {

    var parentPageObj = $('.page[data-page="select-address-page"]');
    var pageObj = $('.page[data-page="add-address-page"]');



    pageObj.find('.btn-save-address').on('click', function () {

        var txtClientName = pageObj.find('.txtClientName').val();
        var txtClientPhone = pageObj.find('.txtClientPhone').val();
        var txtClientAddress = pageObj.find('.txtClientAddress').val();
        var txtClientBulidNo = pageObj.find('.txtClientBulidNo').val();
        var txtLocationLng = pageObj.find('.txtLocationLng').val();
        var txtLocationLat = pageObj.find('.txtLocationLat').val();

        if (txtClientName.length == 0) {
            app.alert("请输入您的姓名");
            return;
        }

        if (txtClientPhone.length != 11) {
            app.alert("请输入正确的手机号");
            return;
        }


		var pdata= {
                ClientName: txtClientName,
                ClientPhone: txtClientPhone,
                ClientAddress: txtClientAddress,
                ClientBulidNo: txtClientBulidNo,
                LocationLng: txtLocationLng,
                LocationLat: txtLocationLat
            };
		var url="customer/ajax.php?action=doCreateContact";

		/*
        $.ajax({
            type: "POST",
            url: "customer/ajax.php?action=doCreateAddress",
            data: {
                ClientName: txtClientName,
                ClientPhone: txtClientPhone,
                ClientAddress: txtClientAddress,
                ClientBulidNo: txtClientBulidNo,
                LocationLng: txtLocationLng,
                LocationLat: txtLocationLat
            },
            dataType: "json",
            success: function (data) {
                console.log(data);


                mainView.router.back();
                ReloadUserAddressList(0);
                //ReloadUserAddressList(parentPageObj.find('.addr-select-list ul'));
            }
        });
        */
		$.post(url,pdata,function(str){
		    var data=eval('('+str+")");
			 console.log(data);
             mainView.router.back();
             ReloadUserAddressList(0);
		});

    });


    //pageObj.find(".txtClientAddress").val("定位中...");

    var baseAddr = "未知区域";
    var map, geolocation;
    //加载地图，调用浏览器定位服务
    map = new AMap.Map('mapContainer', {
        resizeEnable: true
    });
    map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: true,        //显示定位按钮，默认：true
            buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
            buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy: true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        map.addControl(geolocation);
        AMap.event.addListener(geolocation, 'complete', function (data) {

            AMap.service(["AMap.Geocoder"], function () { //加载地理编码
                geocoder = new AMap.Geocoder({
                    radius: 1000,
                    extensions: "all"
                });
                //步骤三：通过服务对应的方法回调服务返回结果，本例中通过逆地理编码方法getAddress回调结果
                geocoder.getAddress(data.position, function (status, result) {
                    //根据服务请求状态处理返回结果
                    if (status == 'error') {
                    }
                    if (status == 'no_data') {
                    }
                    else {
                        console.log(result);
                        baseAddr = result.regeocode.addressComponent.city + " " + result.regeocode.addressComponent.district + " ";
                        if (result.regeocode.pois.length > 0) {
                            baseAddr += result.regeocode.pois[0].name;
                        }
                        pageObj.find(".txtClientAddress").val(baseAddr);
                    }
                });
            });


            pageObj.find('.txtLocationLng').val(data.position.getLng());
            pageObj.find('.txtLocationLat').val(data.position.getLat());

        }); //返回定位信息
    });




    geolocation.getCurrentPosition();













});


//账户充值页面
app.onPageInit('account-recharge-page', function (page) {

    var pageObj = $('.page[data-page="account-recharge-page"]');

    var payType = 1;
    // 支付类型选择
    SelectBoxInit(pageObj.find('.recharge-type-select li'), 'li', true, function (val) {
        payType = val;
    });


    if (CheckIsWeixn()) {
        //如果在微信端就隐藏支付宝支付
        pageObj.find('.recharge-type-select li').eq(0).removeClass("selected").hide();
        pageObj.find('.recharge-type-select li').eq(1).addClass("selected");
        payType = 2;
    }


    pageObj.find('.btn-recharge').on('click', function () {

        var rechargeMoney = pageObj.find('.txtRechargeMoney').val();

        if (rechargeMoney.length == 0) {
            app.alert("请输入充值金额！");
            return;
        }

        if (parseFloat(rechargeMoney) == 0) {
            app.alert("请输入大于0的充值金额！");
            return;
        }

        if (payType == 2 && !CheckIsWeixn()) {
            app.alert("您现在处于浏览器环境中 请在微信中打开网页进行支付！");
            return;
        }


        app.showIndicator();
        $.ajax({
            type: "POST",
            url: "/AccountRecharge",
            data: { PayType: payType, RechargeMoney: parseFloat(rechargeMoney) },
            dataType: "json",
            error: function () {
                app.alert("请求支付失败！");
            },
            success: function (data) {
                if (data.success) {
                    if (data.payType == 'alipay') {
                        app.hideIndicator();
                        window.location.href = "/AccountRecharge_Alipay?oid=" + data.orderId;
                    }
                    else if (data.payType == 'wechatpay') {

                        //公众号支付
                        WeixinJSBridge.invoke('getBrandWCPayRequest', {
                            "appId": data.wechatPay.AppId, //公众号名称，由商户传入
                            "timeStamp": data.wechatPay.TimeStamp, //时间戳
                            "nonceStr": data.wechatPay.NonceStr, //随机串
                            "package": data.wechatPay.Package, //扩展包
                            "signType": "MD5", //微信签名方式:MD5
                            "paySign": data.wechatPay.PaySign //微信签名
                        }, function (res) {
                            app.hideIndicator();
                            if (res.err_msg == "get_brand_wcpay_request:ok") {

                                mainView.router.refreshPreviousPage();

                                app.modal({
                                    title: '温馨提示',
                                    text: '充值成功！',
                                    buttons: [
                                      {
                                          text: '返回',
                                          onClick: function () {
                                              mainView.router.back();
                                          }
                                      }
                                    ]
                                })



                            } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                                //取消了，不操作
                            } else {
                                app.alert("支付失败！原因：" + res.err_msg);
                                mainView.router.loadPage("/UserCenter");
                            }
                        });
                    }
                } else {
                    app.hideIndicator();
                    app.alert(data.msg);
                }
            }
        });
    });

});


//保存评论内容
function SaveReview(orderId, reContext, reStarCount, uploadImageList) {
    $.ajax({
        type: "POST",
        url: "/SaveReviewOrder",
        data: {
            OrderId: orderId,
            ReviewContext: reContext,
            ReviewStar: reStarCount,
            ImageList: uploadImageList
        },
        dataType: "json",
        success: function (data) {
            if (data.success) {
                app.alert("评价成功，感谢您对飞客修的支持！");
            } else {
                app.alert(data.msg);
            }
            mainView.router.back();
        }
    });
}



//加载用户地址列表
function ReloadUserAddressList(defaultSelectedAddrId) {
    var pageObj = $('.page[data-page="select-address-page"]');
    var url="customer/ajax.php?action=getContacts";
	var pdata={};
	var callback=function (str) {
		    var data=eval("("+str+")");
            console.log(data);

            var htmlString = "";
            if (data.list.length > 0) {
                for (var i = 0; i < data.list.length; i++) {
                    htmlString += '<li class="click-active swipeout" data-val="' + data.list[i].id + '">';
                    htmlString += '     <div class="item-content swipeout-content" data-val="' + data.list[i].id + '">';
                    htmlString += '         <div class="item-select"><i class="icon icon-select"></i></div>';
                    htmlString += '         <div class="item-context">';
                    htmlString += '             <div class="item-title">' + data.list[i].realname + ' ' + data.list[i].tel + '</div>';
                    htmlString += '             <div class="item-subtitle">' + data.list[i].address +  '</div>';
                    htmlString += '         </div>';
                    htmlString += '     </div>';
                    htmlString += '     <div class="swipeout-actions-right"><a href="#" data-confirm="确认要删除此地址吗？" class="swipeout-delete">删除</a></div>';
                    htmlString += '</li>';
                }
            } else {
                htmlString += '<div style="padding:15px; text-align:center; color:#999;">您还未添加过地址哦~</div>';
            }


            pageObj.find('.addr-select-list ul').html(htmlString);


            if (defaultSelectedAddrId) {
                pageObj.find('.addr-select-list li[data-val="' + defaultSelectedAddrId + '"]').addClass("selected");
            }
            if (!pageObj.data("update")) {
                SelectBoxInit(pageObj.find('.addr-select-list li .item-content'), '.item-content', true, function (val) {
                    setCookie(COOKIE_KEY_DEFAULT_ADDRESS_ID, val);
                    mainView.router.back();
                    LoadDefaultUserAddress();
                });
            }


            pageObj.find('.swipeout').on('deleted', function () {
                var delAddrId = $(this).data("val");
                $.ajax({
                    type: "POST",
                    url: "/DelUserAddress",
                    data: {
                        AddressId: delAddrId
                    },
                    dataType: "json",
                    success: function (data) {
                    }
                });
            });

        };  //callback
	/*
	$.ajax({
        type: "POST",
        url: "/GetUserAddressList",
        data: {},
        dataType: "json",
        success: 
    }); */
	$.post(url,pdata,callback);
}


function GetFixSelectedIds() {
    var ids = [];
    $.each($('.page[data-page="fix-page"] .select-list-block li.selected'), function (index, obj) {
        ids.push($(obj).data("val"));
    });
    return ids.join(',');
}




function GetRecoverySelectedIds() {
    var ids = [];
    $.each($('.page[data-page="recovery-page"] .sub-level-item.active:not(.color-level-item)'), function (index, obj) {
        ids.push($(obj).data("id"));
    });
    return ids.join(',');
}

function LoadDefaultUserAddress() {
    var defaultAddrId = getCookie(COOKIE_KEY_DEFAULT_ADDRESS_ID);
    var obj = $('.page[data-page="confirm-order-page"] .item-title-address');
    obj.html("加载中...");
    if (defaultAddrId.length > 0) {
		var url="customer/ajax.php?action=getContact";
		var pdata={id:defaultAddrId};
        $.post(url,pdata,function (str) {
			    var data=eval('('+str+')');
                console.log(data);
                if (data.model) {
                    obj.html(data.model.address );
                    obj.attr("data-id", data.model.id);
                } else {
                    obj.html("无");
                    obj.attr("data-id", "-1");
                }
            });
		/*
		$.ajax({
            type: "POST",
            url: "/GetUserAddressModel",
            data: {
                AddressId: defaultAddrId
            },
            dataType: "json",
            success: function (data) {
                console.log(data);
                if (data.model) {
                    obj.html(data.model.ClientAddress + " " + data.model.ClientBulidNo);
                    obj.attr("data-id", data.model.Id);
                } else {
                    obj.html("无");
                    obj.attr("data-id", "-1");
                }
            }
        }); */
    } else {
        obj.html("无");
        obj.attr("data-id", "-1");
    }
}

var mySwiper = app.swiper('.banner-slider', {
    paginationClickable: true,
    spaceBetween: 0,
    centeredSlides: true,
    autoplay: 2500,
    autoplayDisableOnInteraction: false,
    onSlideChangeEnd: function (swiper) {
        $(".swiper-pagination-bullet.swiper-pagination-bullet-active").removeClass("swiper-pagination-bullet-active");
        $(".swiper-pagination-bullet").eq(mySwiper.activeIndex).addClass("swiper-pagination-bullet-active");

    }
});

function CheckIsWeixn() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}

function setCookie(c_name, value) {
    var expiredays = 365;
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) +
    ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
}


//取回cookie
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}


//时间转换前位加零

function dFormat(i) { return i < 10 ? "0" + i.toString() : i; }
//转换json传输date
function time_string(d) {
    var ar_date = [d.getFullYear(), d.getMonth() + 1, d.getDate()];
    var result = "";
    result += dFormat(d.getMonth() + 1) + "-";
    result += dFormat(d.getDate()) + " ";
    return result;
}


function location_to(url){

	window["curr_href"]=window.location.href;
	window.location.href=url;
}


